import {Component, Inject, OnDestroy, OnInit} from '@angular/core';
import {FarmService} from '../../../../../service/farm.service';
import {MAT_DIALOG_DATA, MatDialog, MatDialogRef} from '@angular/material';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {LimitedFarm} from '../../limited-farm';
import {MyValidators} from '../../../../../utils/validator/rang';

@Component({
  selector: 'app-farm-coordinate',
  templateUrl: './farm-coordinate.component.html',
  styleUrls: ['./farm-coordinate.component.css']
})
export class FarmCoordinateComponent implements OnInit, OnDestroy {
  public dialogResult: DialogResult;
  public error: any;
  public farm: LimitedFarm
  /**
   * FormGroup对象
   *
   * @type {FormGroup}
   * @memberof BladeContainerBase
   */
  public formGroup: FormGroup;

  public formErrors = {
    'posx': '',
    'posy': ''
  };

  public validationMessages = {
    'posx': {
      'required': 'X轴坐标不能为空。',
      'rang': 'X轴坐标范围是-10~110的数值。',
    },
    'posy': {
      'required': 'Y轴坐标不能为空。',
      'rang': 'Y轴坐标范围是-10~110的数值。',
    }
  };

  constructor(
    private fb: FormBuilder,
    private farmService: FarmService,
    private dialog: MatDialog,
    private dialogRef: MatDialogRef<FarmCoordinateComponent>,
    @Inject(MAT_DIALOG_DATA) private data: any) {
    this.farm = data.farm;
  }

  ngOnInit() {
    this.formGroup = this.fb.group({
      'posx': [this.farm.posx, [
        Validators.required,
        MyValidators.numberRang(-10, 100),
      ]],
      'posy': [this.farm.posy, [
        Validators.required,
        MyValidators.numberRang(-10, 100),
      ]],
    });
    this.subscribeChanges();
  }

  ngOnDestroy(): void {
    if (this.dialogResult == null) {
      this.farm.posx = this.data.old.posx;
      this.farm.posy = this.data.old.posy;
    }
  }

  /**
   * 订阅表单值变化
   *
   *
   * @memberof BladeContainerBase
   */
  subscribeChanges(): void {
    if (this.formGroup != null) {
      this.formGroup.valueChanges
        .subscribe(data => this.onValueChanged(data));
      this.formGroup.statusChanges
        .subscribe(data => this.onStatusChanged(data));
      this.formGroup.patchValue(this.farm);
    }
  }

  /**
   * 表单值变化事件
   *
   * @param {any} [data]
   *
   * @memberof BladeContainerBase
   */
  onValueChanged(data?: any): void {
    const form = this.formGroup;
    for (const field in this.formErrors) {
      this.formErrors[field] = '';
      const control = form.get(field);
      if (control && !control.valid) {
        const messages = this.validationMessages[field];
        for (const key in control.errors) {
          this.formErrors[field] = messages[key];
        }
      }
    }
    if (this.formGroup.valid) {
      let formValue = this.formGroup.value as LimitedFarm;
      this.farm.posx = formValue.posx;
      this.farm.posy = formValue.posy;
    }
  }

  /**
   * 表单状态变化事件
   *
   * @param {any} [data]
   *
   * @memberof BladeContainerBase
   */
  onStatusChanged(data?: any): void {
    if (this.formGroup.status.toLowerCase() == 'invalid') {
      this.onValueChanged(data);
    }
  }

  /**
   *
   *
   *
   * @memberof DialogComponent
   */
  ok() {
    let formValue = this.formGroup.value as LimitedFarm;
    this.farmService.updateFarmPos({farmId: this.farm.farmId, posx: formValue.posx, posy: formValue.posy})
      .then(res => {
        if (res) {
          this.dialogResult = DialogResult.ok
          this.dialogRef.close(DialogResult.ok);
        }
        else {
          this.error = '保存失败'

        }
      })
      .catch(error => {
        this.error = error
      });
  }

  /**
   *
   *
   *
   * @memberof DialogComponent
   */
  no() {
    this.farm.posx = this.data.old.posx;
    this.farm.posy = this.data.old.posy;
    this.dialogResult = DialogResult.no
    this.dialogRef.close(this.dialogResult);
  }
}

export enum DialogResult {
  ok,
  no,
}
